<template>
  <div class="review-report-list">
    <el-card class="report-card">
      <template #header>
        <div class="card-header">
          <span>评价举报管理</span>
          <div class="header-actions">
            <el-select
              v-model="searchForm.status"
              placeholder="处理状态"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option label="待处理" value="PENDING" />
              <el-option label="已处理" value="RESOLVED" />
              <el-option label="已拒绝" value="REJECTED" />
            </el-select>
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入举报原因或评价内容"
              style="width: 300px; margin-right: 10px"
              clearable
              :maxlength="200"
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        :data="reportList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="reviewId" label="评价ID" width="100" />
        <el-table-column prop="user.name" label="举报用户" width="120" />
        <el-table-column prop="reason" label="举报原因" show-overflow-tooltip />
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="举报时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              size="small"
              type="success"
              @click="handleResolve(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              处理
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleReject(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看举报详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="举报详情"
      width="800px"
    >
      <div class="report-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="举报ID">{{ currentReport.id }}</el-descriptions-item>
          <el-descriptions-item label="举报用户">{{ currentReport.user?.name }}</el-descriptions-item>
          <el-descriptions-item label="举报原因">{{ currentReport.reason }}</el-descriptions-item>
          <el-descriptions-item label="详细描述">{{ currentReport.description }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTagType(currentReport.status)">
              {{ formatStatus(currentReport.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="举报时间">{{ currentReport.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ currentReport.handledAt }}</el-descriptions-item>
        </el-descriptions>

        <div class="review-preview" v-if="currentReview">
          <h4>被举报评价</h4>
          <el-card>
            <div class="review-header">
              <div class="user-info">
                <el-avatar :src="currentReview.user.avatar" size="small" />
                <span class="user-name">{{ currentReview.user.name }}</span>
              </div>
              <el-rate
                v-model="currentReview.rating"
                disabled
                size="small"
              />
            </div>
            <div class="review-content">{{ currentReview.content }}</div>
            <div class="review-tags">
              <el-tag
                v-for="tag in currentReview.tags"
                :key="tag"
                style="margin-right: 10px; margin-bottom: 10px;"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="review-footer">
              <span class="review-time">{{ formatTime(currentReview.createdAt) }}</span>
              <el-tag type="success" v-if="currentReview.isFeatured">精选</el-tag>
              <el-tag type="warning" v-if="currentReview.status === 'PENDING'">待审核</el-tag>
              <el-tag type="success" v-else-if="currentReview.status === 'APPROVED'">已通过</el-tag>
              <el-tag type="danger" v-else-if="currentReview.status === 'REJECTED'">已拒绝</el-tag>
              <el-tag type="info" v-else-if="currentReview.status === 'HIDDEN'">已隐藏</el-tag>
            </div>
          </el-card>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处理举报对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="处理举报"
      width="600px"
    >
      <el-form
        ref="handleFormRef"
        :model="handleForm"
        :rules="handleRules"
        label-width="100px"
      >
        <el-form-item label="处理结果" prop="status">
          <el-radio-group v-model="handleForm.status">
            <el-radio label="RESOLVED">处理举报</el-radio>
            <el-radio label="REJECTED">拒绝举报</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理操作" prop="action" v-if="handleForm.status === 'RESOLVED'">
          <el-radio-group v-model="handleForm.action">
            <el-radio label="HIDE">隐藏评价</el-radio>
            <el-radio label="DELETE">删除评价</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理说明" prop="remark">
          <el-input
            v-model="handleForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle" :loading="handleLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ReviewReport, CourseReview } from '@/types/api/review'
import { reviewManagementApi } from '@/api/modules/review'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const reportList = ref<ReviewReport[]>([])
const currentReport = ref<ReviewReport>({
  id: 0,
  reviewId: 0,
  userId: 0,
  reason: '',
  status: 'PENDING',
  createdAt: ''
})
const currentReview = ref<CourseReview | null>(null)

// 搜索表单
const searchForm = reactive({
  status: '',
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)
const handleDialogVisible = ref(false)
const handleLoading = ref(false)
const handleFormRef = ref()
const currentReportId = ref(0)

// 处理表单数据
const handleForm = reactive({
  status: 'RESOLVED' as 'RESOLVED' | 'REJECTED',
  action: 'HIDE' as 'HIDE' | 'DELETE',
  remark: ''
})

// 表单验证规则
const handleRules = {
  status: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ],
  action: [
    { required: true, message: '请选择处理操作', trigger: 'change' }
  ]
}

// 获取举报列表
const getReportList = async () => {
  try {
    loading.value = true
    const response = await reviewManagementApi.getReviewReports({
      status: searchForm.status as 'PENDING' | 'RESOLVED' | 'REJECTED' | undefined,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    reportList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取举报列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getReportList()
}

// 刷新列表
const refreshList = () => {
  getReportList()
}

// 查看举报详情
const handleView = async (row: ReviewReport) => {
  currentReport.value = row
  // 模拟获取评价详情
  currentReview.value = {
    id: row.reviewId,
    courseId: 1,
    userId: 301,
    user: {
      id: 301,
      name: '用户B',
      avatar: ''
    },
    rating: 3,
    content: '这是一条被举报的评价内容...',
    images: [],
    tags: ['一般'],
    isAnonymous: false,
    isFeatured: false,
    helpfulCount: 0,
    isHelpful: false,
    status: 'APPROVED',
    createdAt: '2025-10-20T15:20:00Z',
    replies: []
  }
  detailDialogVisible.value = true
}

// 处理举报
const handleResolve = async (row: ReviewReport) => {
  formUtils.handleDeleteConfirm(`举报 "${row.reason}"`, async () => {
    currentReportId.value = row.id
    handleForm.status = 'RESOLVED'
    handleForm.action = 'HIDE'
    handleForm.remark = ''
    handleDialogVisible.value = true
  }, {
    title: '处理举报',
    successMessage: '操作成功',
    errorMessage: '操作失败'
  })
}

// 拒绝举报
const handleReject = async (row: ReviewReport) => {
  formUtils.handleDeleteConfirm(`举报 "${row.reason}"`, async () => {
    currentReportId.value = row.id
    handleForm.status = 'REJECTED'
    handleForm.action = 'HIDE'
    handleForm.remark = ''
    handleDialogVisible.value = true
  }, {
    title: '拒绝举报',
    successMessage: '操作成功',
    errorMessage: '操作失败'
  })
}

// 提交处理结果
const submitHandle = async () => {
  if (!handleFormRef.value) return

  try {
    await handleFormRef.value.validate()

    // 使用防重复提交保护
    await preventDuplicateSubmit(`handle_report_${currentReportId.value}`, async () => {
      handleLoading.value = true
      try {
        await reviewManagementApi.handleReport(currentReportId.value, {
          status: handleForm.status,
          action: handleForm.action
        })
        ElMessage.success('处理成功')
        handleDialogVisible.value = false
        refreshList()
      } catch (error: any) {
        ElMessage.error('处理失败')
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        handleLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getReportList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getReportList()
}

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待处理',
    'RESOLVED': '已处理',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'PENDING': 'warning',
    'RESOLVED': 'success',
    'REJECTED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  getReportList()
})
</script>

<style scoped>
.review-report-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.review-preview {
  margin-top: 20px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-name {
  margin-left: 10px;
  font-weight: bold;
}

.review-content {
  margin-bottom: 10px;
  line-height: 1.5;
}

.review-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}
</style>
